from django.shortcuts import render,redirect,HttpResponse

# Create your views here.

def islogin(func):
	def inner(request,*args,**kwargs):
		if not request.session.get('isLogin',False):  #如果cookie不存在就跳转到登录页面
			return render(request, 'login.html')
		else:  #否则，自动跳回原本的函数
			return func(request,*args,**kwargs)
	return inner

def login(request):
	import json
	result = {'status':True,'message':None,'data':None}

	if request.method == 'GET':
		return render(request,'login.html')

	elif request.method == 'POST':
		u = request.POST.get('user')
		p = request.POST.get('pwd')

		if u == 'Beam' and p == '123456':
			request.session['username'] = u
			request.session['isLogin'] = True

			result['status'] = request.session.get('isLogin')
			result['message'] = request.session['username']
		else:
			result['status'] = request.session.get('isLogin')
			result['message'] = request.session['username']
		return HttpResponse(json.dumps(result))
	else:
		return HttpResponse('404')

@islogin
def index(request):
	return render(request,'index.html',{'username':request.session.get('username',None)})

def logout(request):
	request.session.clear()
	return redirect('/app/index/')

#局部视图缓存
# from django.views.decorators.cache import cache_page
# @cache_page(1*10)
def cachetest(request):
	import time
	utctime = time.time()
	return render(request,'cache.html',{'utctime':utctime})

import re
from django.core.exceptions import ValidationError
def mobile_validate(value):
	mobile_re = re.compile(r'^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$')
	if not mobile_re.match(value):
		raise ValidationError('手机号码格式有误')

from django import forms  #使用django的forms必须先导入这个模块

class RegisterForm(forms.Form):
	user_type_choice = ((0,u'普通用户'),(1,u'高级用户'),)
	user_type = forms.IntegerField(widget=forms.widgets.Select(choices=user_type_choice,attrs={'class':'form-control'}))
	username = forms.CharField(max_length=18,
	                           min_length=8,
	                           error_messages={'required':u'用户名不能为空','min_length':u"长度不能小于8位",'max_length':u"长度不能多于18位"},
	                           widget=forms.TextInput(attrs={'class': "form-control",'placeholder': u'用户名8-18字符'}),
	                           label="用户名")
	passwd = forms.CharField(max_length=18,
	                         min_length=6,
	                         error_messages={'required':u'密码不能为空','min_length':u"长度不能小于6位",'max_length':u"长度不能多于18位"},
	                         widget=forms.PasswordInput(attrs={'class': "form-control",'placeholder': u'密码6-18字符'}),
	                         label="密码")
	email = forms.EmailField(required=False,  #是否可以为空，如果True，后面的error_messages的required就会显示
	                         error_messages={'required':u"邮箱不能为空",'invalid':u'邮箱格式错误',},
	                         widget=forms.TextInput(attrs={'class':"form-control",'placeholder':u'邮箱'}),
	                         label=u'邮箱地址')
	phone = forms.CharField(validators=[mobile_validate, ],
	                        error_messages={'required': u'手机不能为空'},
	                        widget=forms.TextInput(attrs={'class': "form-control",
	                        'placeholder': u'手机号码'}),
	                        label=u'手机号码')
	address = forms.CharField(required=False,
	                          max_length=256,
	                          widget=forms.widgets.Textarea(
		                       attrs={'class': "form-control no-radius", 'placeholder': u'地址', 'rows': 1}),
	                          label=u'家庭地址')

def register(request):
	if request.method == 'GET':
		obj = RegisterForm()
		return render(request,'register.html',{'obj':obj})
	elif request.method == 'POST':
		obj = RegisterForm(request.POST)
		if obj.is_valid():  #判断值是否True
			print(obj.cleaned_data)
			#比如这个动作是增加一条数据到数据库的话，比如表叫user，这样可以快速新增数据
			#models.user.objects.create(**obj.cleaned_data)
			return HttpResponse('添加成功')

		else:
			return render(request,'register.html',{'obj':obj})
	else:
		return HttpResponse('404')


